using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;

namespace rudp
{
	public sealed class MessageManager
	{
		private static volatile MessageManager instance;
   		private static object syncRoot = new Object();

   		private MessageManager ()
		{		
		}

		public static MessageManager Instance
		{
			get 
		    {
		    	if (instance == null) 
		        {
		        	lock (syncRoot) 
		            {
		               if (instance == null) 
		                  instance = new MessageManager();
		            }
		        }

		        return instance;
			}
		}

		public List<Message> CreateMessagePacketList( byte[] data, int count, int mtuSize )
		{
            List<Message> messages = new List<Message>();
            byte 	      messageIndex = 0;
			int 		  bytesRead = 0;

			if( data.Length < mtuSize ) 
			{
				
				messages.Add( new Message{ 
					Data = data,
					Index = 0,
					Flags = MessageFlags.Data | MessageFlags.ReceiptRequest,
					DataLength = (ushort)data.Length
				});
			} 
			else 
			{
				using( MemoryStream dataStream = new MemoryStream( data ))
				{
					byte[] buffer = new byte[mtuSize];
		
					bytesRead = dataStream.Read( buffer, 0, (int)mtuSize );


					while( bytesRead > 0 && messageIndex < count )
					{						
						Message message = new Message();
						message.Flags = MessageFlags.Data;
						message.Data = buffer;
						message.Index = messageIndex;
						message.DataLength = (ushort)bytesRead;

						messages.Add( message );
						messageIndex++;

						bytesRead = dataStream.Read( buffer, 0, (int)mtuSize );
					}
				}
			}

			return messages;
		}

		public Message CreateReceiptMessagePacket ( List<Message> packets, int count )
		{
            List<int> missingMessages = new List<int>();

			MessageReceipt messageReceipt = new MessageReceipt();
			messageReceipt.Count = (byte)missingMessages.Count;
	
			byte[] data = messageReceipt.ToByteArray();

			Message receipt = new Message();
			receipt.Data = data;
			receipt.DataLength = (ushort)data.Length;
			receipt.Flags = MessageFlags.ReceiptResponse;
			receipt.Id = packets[0].Id;
									  
			return receipt;
		}
	}
}

